<template>
  <div>
    <el-row :gutter="10" class="mb8">

    </el-row>

    <el-table v-loading="loading" :data="leaseaccperList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="自增ID" align="center" prop="id" /> -->
      <!-- <el-table-column label="租户合同ID" align="center" prop="leaseContractId" > -->
      <el-table-column label="帐期" width="80" align="center" prop="issueNumber">
        <template #default="scope">
          {{ scope.row.issueNumber || '-' }}
        </template>
      </el-table-column>


      <!-- <el-table-column label="租户合同ID" width="180">
        <template #default="scope">
          <div v-if="!scope.row.isEdit">{{ scope.row.leaseContractId }}</div>
          <el-input v-else v-model="scope.row.leaseContractId" size="small" />
        </template>
</el-table-column> -->

      <el-table-column label="开始时间" align="center" prop="paymentTermStartTime" width="180">
        <template #default="scope">
          <div v-if="!scope.row.isEdit">{{ parseTime(scope.row.paymentTermStartTime, '{y}-{m}-{d}') }}</div>
          <!-- <el-input v-model="scope.row.totalDay" size="small" /> -->
          <el-date-picker v-else clearable v-model="scope.row.paymentTermStartTime" type="date"
            value-format="YYYY-MM-DD" placeholder="请选择合同开始时间" @change="calculateDays(scope.row)" style="width: 100%;">
          </el-date-picker>
        </template>

      </el-table-column>
      <el-table-column label="结束时间" align="center" prop="paymentTermEndTime" width="180">
        <template #default="scope">
          <div v-if="!scope.row.isEdit">{{ parseTime(scope.row.paymentTermEndTime, '{y}-{m}-{d}') }}</div>
          <el-date-picker v-else clearable v-model="scope.row.paymentTermEndTime" type="date" value-format="YYYY-MM-DD"
            placeholder="请选择合同结束时间" :disabled-date="(time) => disabledEndDate(time, scope.row.paymentTermStartTime)"
            @change="calculateDays(scope.row)" style="width: 100%;">
          </el-date-picker>

        </template>
      </el-table-column>
      <el-table-column label="天数" align="center" prop="totalDay">
        <template #default="scope">
          <div>{{ scope.row.totalDay }}天</div>
        </template>
      </el-table-column>

      <el-table-column label="租户管理费" align="center" prop="tenantManagementFee">
        <template #default="scope">
          <div v-if="!scope.row.isEdit">{{ (Number(scope.row.tenantManagementFee) || 0).toFixed(2) }}元</div>
          <el-input v-else v-model="scope.row.tenantManagementFee" size="small" type="number" placeholder="请输入金额（元）">
            <template #append>元</template>
          </el-input>
        </template>
      </el-table-column>

      <el-table-column label="业主管理费" align="center" prop="homeownersManagementFee">
        <template #default="scope">
          <div v-if="!scope.row.isEdit">{{ (Number(scope.row.homeownersManagementFee) || 0).toFixed(2) }}元</div>
          <el-input v-else v-model="scope.row.homeownersManagementFee" size="small" type="number" placeholder="请输入金额（元）">
            <template #append>元</template>
          </el-input>
        </template>
      </el-table-column>

      <el-table-column label="租户租金" align="center" prop="tenantRent">
        <template #default="scope">
          <div v-if="!scope.row.isEdit">{{ (Number(scope.row.tenantRent) || 0).toFixed(2) }}元</div>
          <el-input v-else v-model="scope.row.tenantRent" size="small" type="number" placeholder="请输入金额（元）">
            <template #append>元</template>
          </el-input>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <div v-if="scope.row.isTransactionStatus === 0 && !props.disabled">
            <!-- 编辑状态 -->
            <template v-if="scope.row.isEdit">
              <el-button type="success" link @click="handleConfirm(scope.row)">确认</el-button>
              <el-popconfirm title="确认删除该账期？" @confirm="() => handleDelete(scope.row)">
                <template #reference>
                  <el-button link type="danger">删除</el-button>
                </template>
              </el-popconfirm>
            </template>
            <!-- 显示状态 -->
            <template v-else>
              <el-button type="primary" link @click="handleEdit(scope.row)">编辑</el-button>
              <el-button type="primary" link @click="handleCopy(scope.row)">复制</el-button>
              <el-popconfirm title="确认删除该账期？" @confirm="() => handleDelete(scope.row)">
                <template #reference>
                  <el-button link type="danger">删除</el-button>
                </template>
              </el-popconfirm>
            </template>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <!-- 新增按钮移到底部 -->
    <div class="mt-4" v-if="!props.disabled">
      <el-button plain class="w-full" @click="handleAdd">新增账期</el-button>
    </div>
  </div>
</template>

<script setup name="LeaseAccountPeriod">
import { listLeaseaccper, getLeaseaccper, delLeaseaccper, addLeaseaccper, updateLeaseaccper } from "@/api/fang/leaseaccper"
import { convertFenToYuan, convertYuanToFen } from "@/utils/tools"
import modal from "@/plugins/modal"

// <!-- <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['fang:leaseaccper:edit']">修改</el-button>
// <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['fang:leaseaccper:remove']">删除</el-button> -->

const leaseaccperList = ref([])

const loading = ref(true)

const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)



// 获取用于提交的账期数据（转换为接口格式）
function getSubmitData() {
  return leaseaccperList.value
    .filter(item => !item.isEdit) // 只提交已确认的数据
    .map(item => {
      return {
        paymentTermStartTime: item.paymentTermStartTime,
        paymentTermEndTime: item.paymentTermEndTime,
        tenantManagementFee: convertYuanToFen(item.tenantManagementFee), // 转换为分
        homeownersManagementFee: convertYuanToFen(item.homeownersManagementFee), // 转换为分
        tenantRent: convertYuanToFen(item.tenantRent), // 转换为分
        totalDay: item.totalDay,
        issueNumber: item.issueNumber || 0
      }
    })
}

defineExpose({
  leaseaccperList, // 暴露列表数据
  getSubmitData // 暴露获取提交数据的方法
});


const props = defineProps({
  // 定义 Prop 的名称和类型
  leaseContractId: {
    type: Number,
    default: '默认值'
  },
  // 是否禁用编辑（只读模式）
  disabled: {
    type: Boolean,
    default: false
  }
});

console.log("props.leaseContractId=" + props.leaseContractId)

const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 100,
    leaseContractId: null,
    paymentTermStartTime: null,
    paymentTermEndTime: null,
    totalDay: null,
    tenantManagementFee: null,
    homeownersManagementFee: null,
    tenantRent: null,
  },

  form: {},
  rules: {
  }
})

const { queryParams, form, rules } = toRefs(data)

// 计算并设置账期序号
function updateIssueNumbers() {
  const sortedList = [...leaseaccperList.value].sort((a, b) => {
    if (!a.paymentTermStartTime || !b.paymentTermStartTime) return 0
    return new Date(a.paymentTermStartTime) - new Date(b.paymentTermStartTime)
  })
  sortedList.forEach((item, index) => {
    item.issueNumber = index + 1
  })
}

/** 查询租赁合同帐期列表 */
function getList() {
  // 如果没有 leaseContractId（新建合同时），不查询，直接返回
  if (!props.leaseContractId || props.leaseContractId === '默认值') {
    loading.value = false
    leaseaccperList.value = []
    return
  }
  
  loading.value = true
  queryParams.value.leaseContractId = props.leaseContractId
  listLeaseaccper(queryParams.value).then(response => {
    // 将后端返回的数据转换为前端显示格式（分转元）
    leaseaccperList.value = (response.rows || []).map(item => {
      return {
        ...item,
        // 将所有金额字段从分转换为元（前端统一使用元）
        tenantManagementFee: convertFenToYuan(item.tenantManagementFee),
        homeownersManagementFee: convertFenToYuan(item.homeownersManagementFee),
        tenantRent: convertFenToYuan(item.tenantRent),
        // 确保有 isTransactionStatus 字段（0可编辑，1已生成不可编辑）
        isTransactionStatus: item.isTransactionStatus ?? 0
      }
    })

    // 计算账期序号
    updateIssueNumbers()

    total.value = response.total || 0
    loading.value = false
  }).catch(() => {
    loading.value = false
    leaseaccperList.value = []
  })
}



// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 - 复制最后一行信息并插入到最后 */
function handleAdd() {
  if (leaseaccperList.value.length === 0) {
    // 如果没有数据，创建空行
    const newRow = {
      id: 0,
      isEdit: true,
      paymentTermStartTime: null,
      paymentTermEndTime: null,
      totalDay: 0,
      tenantManagementFee: 0, // 前端显示和输入使用元
      homeownersManagementFee: 0,
      tenantRent: 0,
      isTransactionStatus: 0,
      issueNumber: leaseaccperList.value.length + 1
    }
    leaseaccperList.value.push(newRow)
  } else {
    // 复制最后一行信息
    const lastRow = leaseaccperList.value[leaseaccperList.value.length - 1]
    const newRow = {
      id: 0,
      isEdit: true,
      paymentTermStartTime: lastRow.paymentTermStartTime,
      paymentTermEndTime: lastRow.paymentTermEndTime,
      totalDay: lastRow.totalDay,
      tenantManagementFee: lastRow.tenantManagementFee ?? 0, // 使用元
      homeownersManagementFee: lastRow.homeownersManagementFee,
      tenantRent: lastRow.tenantRent,
      isTransactionStatus: 0,
      issueNumber: leaseaccperList.value.length + 1
    }
    leaseaccperList.value.push(newRow)
    updateIssueNumbers()
  }
}

/** 复制功能 - 复制本行信息并插入到下一行 */
function handleCopy(row) {
  const currentIndex = leaseaccperList.value.findIndex(item => item === row)
  const newRow = {
    id: 0,
    isEdit: true,
    paymentTermStartTime: row.paymentTermStartTime,
    paymentTermEndTime: row.paymentTermEndTime,
    totalDay: row.totalDay,
    tenantManagementFee: row.tenantManagementFee ?? 0, // 使用元
    homeownersManagementFee: row.homeownersManagementFee,
    tenantRent: row.tenantRent,
    isTransactionStatus: 0
  }
  leaseaccperList.value.splice(currentIndex + 1, 0, newRow)
  updateIssueNumbers()
}

function handleEdit(row) {
  // 备份原始数据，用于取消时恢复
  row.isEdit = true;
}

/** 确认按钮操作 - 验证并保存 */
function handleConfirm(row) {
  // 验证当前行数据
  const validationResult = validateRow(row)
  if (!validationResult.isValid) {
    modal.msgError(validationResult.message)
    return
  }

  // 验证通过，退出编辑状态
  row.isEdit = false
}

/** 验证单行数据 */
function validateRow(row) {
  // 必填字段验证
  if (!row.paymentTermStartTime) {
    return { isValid: false, message: "开始时间不能为空" }
  }
  if (!row.paymentTermEndTime) {
    return { isValid: false, message: "结束时间不能为空" }
  }
  if (!row.tenantRent && row.tenantRent !== 0) {
    return { isValid: false, message: "租金不能为空" }
  }
  if (!row.tenantManagementFee && row.tenantManagementFee !== 0) {
    return { isValid: false, message: "租客管理费不能为空" }
  }
  if (!row.homeownersManagementFee && row.homeownersManagementFee !== 0) {
    return { isValid: false, message: "业主管理费不能为空" }
  }

  // 金额验证
  const rent = Number(row.tenantRent)
  const tenantFee = Number(row.tenantManagementFee)
  const ownerFee = Number(row.homeownersManagementFee)

  if (rent < 0 || rent > 50000) {
    return { isValid: false, message: "租金金额必须在0-50000元之间" }
  }
  if (tenantFee < 0) {
    return { isValid: false, message: "租客管理费不能为负数" }
  }
  if (ownerFee < 0) {
    return { isValid: false, message: "业主管理费不能为负数" }
  }
  if (tenantFee > rent * 0.5) {
    return { isValid: false, message: "租客管理费建议不超过租金的50%" }
  }
  if (ownerFee > rent * 0.5) {
    return { isValid: false, message: "业主管理费建议不超过租金的50%" }
  }

  // 时间验证
  const startDate = new Date(row.paymentTermStartTime)
  const endDate = new Date(row.paymentTermEndTime)

  if (startDate >= endDate) {
    return { isValid: false, message: "开始时间必须早于结束时间" }
  }

  // 计算天数
  const days = Math.ceil((endDate - startDate) / (1000 * 60 * 60 * 24))
  if (days < 0) {
    return { isValid: false, message: "结束时间必须晚于或等于开始时间" }
  }

  // 更新天数
  row.totalDay = days

  // 更新账期序号
  updateIssueNumbers()

  // 验证账期连续性
  const currentIndex = leaseaccperList.value.findIndex(item => item === row)
  const sortedList = [...leaseaccperList.value].sort((a, b) => new Date(a.paymentTermStartTime) - new Date(b.paymentTermStartTime))

  for (let i = 0; i < sortedList.length - 1; i++) {
    const current = sortedList[i]
    const next = sortedList[i + 1]

    if (current.isEdit || next.isEdit) continue // 跳过编辑中的行

    const currentEnd = new Date(current.paymentTermEndTime)
    const nextStart = new Date(next.paymentTermStartTime)
    const expectedNextStart = new Date(currentEnd.getTime() + 24 * 60 * 60 * 1000)

    if (nextStart.getTime() !== expectedNextStart.getTime()) {
      return { isValid: false, message: `第${i + 1}期结束日期+1天应等于第${i + 2}期开始日期` }
    }
  }

  return { isValid: true, message: "" }
}

/** 计算天数 */
function calculateDays(row) {
  if (row.paymentTermStartTime && row.paymentTermEndTime) {
    const startDate = new Date(row.paymentTermStartTime)
    const endDate = new Date(row.paymentTermEndTime)
    const days = Math.ceil((endDate - startDate) / (1000 * 60 * 60 * 24))
    row.totalDay = days > 0 ? days : 0
  }
}

/** 禁用结束日期 - 不能早于开始时间 */
function disabledEndDate(time, startTime) {
  if (!startTime) return false
  const startDate = new Date(startTime)
  return time.getTime() < startDate.getTime()
}

/** 提交按钮 */
function submitForm() {
  // 此方法暂未使用，保留备用
}

/** 删除按钮操作 */
function handleDelete(row) {
  const index = leaseaccperList.value.findIndex(item => item === row)
  if (index > -1) {
    leaseaccperList.value.splice(index, 1)
  }
}

/** 导出按钮操作 */
function handleExport() {
  // 导出功能待实现
}

getList()
</script>
